package dao

import (
	"RedWork/model"
	"errors"
	"fmt"
	"time"
)

type FocusGoodRes struct {
	UserID int `json:"user_id"`
	model.PhoneInfo
	AddTime time.Time
}

func AddFocusGood(uid, gid string) (err error) {
	sqlStr :=
		"insert into focus_good_db (user_id, good_idfk) values (?, ?)"
	_, err = DB.Exec(sqlStr, uid, gid)
	fmt.Println(time.Now())
	if err != nil {
		fmt.Println("AddFocusGood err ", err)
		return err
	}
	return
}

func QueryFocusGood(uid int) (data []FocusGoodRes) {
	sqlStr :=
		"SELECT a.user_id, a.create_time, b.good_id, b.good_name, b.good_image, b.brand, b.screen_size, b.charging_power, b.price, b.store_id " +
			"FROM focus_good_db a, phone_info b " +
			"WHERE a.good_idfk = b.good_id && a.user_id = ?"
	rows, err := DB.Query(sqlStr, uid)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	defer rows.Close()
	for rows.Next() {
		var temp FocusGoodRes
		err = rows.Scan(
			&temp.UserID,
			&temp.AddTime,
			&temp.GoodID,
			&temp.GoodName,
			&temp.GoodImage,
			&temp.Brand,
			&temp.ScreenSize,
			&temp.ChargingPower,
			&temp.Price,
			&temp.StoreID,
		)
		if err != nil {
			fmt.Println(err)
			return nil
		}
		data = append(data, temp)
	}
	return
}

func DeleteFocusGood(uid, gid string) (err error) {
	sqlStr := "DELETE FROM focus_good_db WHERE (user_id = ? && good_idfk = ?)"
	fmt.Println("DeleteFocusGood " + uid + "  " + gid)
	res, err := DB.Exec(sqlStr, uid, gid)
	if err != nil {
		fmt.Println(err)
		return
	}
	affected, err := res.RowsAffected()
	if affected == 0 {
		err = errors.New("no result")
	}
	return
}
